import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

public class StorageHandler {
	//Log
	private static Logger logger;
	private static final boolean D = true;
	
	private String name;
	private FileHandler fh;
	private FileWriter fileWriter;
	private FileReader fileReader;
	
	public StorageHandler(String name){
		this.name = name;
		fileWriter = null;
		fileReader = null;
		logger = Logger.getLogger("pckt.Test-StorageHandlerJava");
		
		try {
			fh = new FileHandler("Log_StorageHandler.txt");
		} catch (Exception e) {
			logger.warning("Couldn't open file handler for logger: StoraHandler");
		}
		logger.addHandler(fh);
	}
	
	/**
	 * Open the file for writing
	 * @return True in success. False otherwise
	 */
	public boolean openWrite(boolean append){
		try {
			fileWriter = new FileWriter(name, append);
		} catch (Exception e) {
			if (D) logger.warning("Excpetion: couldn't open the file writer.");
			return false;
		}
		//logger.warning("Abriu pra escrita com nome: "+name);
		return true;
	}
	
	/**
	 * Open the file for reading
	 * @return True in success. False otherwise
	 */	
	public boolean openRead(){
		try {
			fileReader = new FileReader(name);
		} catch (Exception e) {
			if (D) logger.warning("Excpetion: couldn't open the file reader.");
			return false;
		}
		return true;
	}
	
	/**
	 * Write a string to the file
	 * @param str The string to be written
	 * @return True on success. False otherwise
	 */
	public boolean write(String str){
		if (fileWriter == null) openWrite(false);
		
		try {
			fileWriter.write(str);
			//logger.warning("Escreveu efetivamente: "+str);
		} catch (Exception e) {
			if (D) logger.warning("Excpetion: couldn't write to the file writer.");
			return false;
		}
		return true;
	}
	
	/**
	 * Read a string from the file
	 * @return The string read
	 */
	public String read(){
		if (fileReader == null) openRead();
		
		char[] buffer = new char[1024];
		try {
			fileReader.read(buffer);
		} catch (Exception e){
			if (D) logger.warning("Excpetion: couldn't read the file.");
			return null;
		}
		String str = new String(buffer);
		return(str);
	}
	
	public boolean close(){
		try {
			if (fileWriter != null)fileWriter.close();
			this.flush();
			fileWriter = null;
			if (fileReader != null) fileReader.close();
			fileReader = null;
		} catch (IOException e) {
			if (D) logger.warning("Excpetion: couldn't close the fileWriter/fileReader.");
			return false;
		}
		return true;
	}
	
	public void flush(){
		if (fileWriter != null)
			try {
				fileWriter.flush();
			} catch (IOException e) {}
	}

}
